import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import checkToken from './checkToken'
import axios from '@assets/request/index';
import {store} from '../store/index'
export const Store=store
//出事化数据
import {getData} from '@assets/request/setData';
const routes: Array<RouteRecordRaw> = [
	{
		path:'/',
		name:'Login',
		component: () => import('../views/Login/index.vue')
	},
	{
		path:'/singup',
		name:'singup',
		component: () => import('../views/Login/singup.vue')
	},
	{
		path:'/default',
		name:'404',
		component:()=>import('./404.vue')
	},
	{
		path:'/Home',
		name:'/Home',
		redirect:'/Home/Shop',
		component: () => import('../views/Home/index.vue'),
		children:[
			{
        path: 'Shop',
        component: () => import('../views/Home/Shop/index.vue')
      },
			{
			  path: 'News',
			  component: () => import('../views/Home/News/index.vue'),
			},
			{
			  path: 'My',
			  component: () => import('../views/Home/My/index.vue'),
			},
			{
				path:'CommodityManagement',
				component:()=>import('../components/context/CommodityManagement/index.vue')
			},
			{
				path:'analysis',
				component:()=>import('../components/context/analysis/index.vue')
			}
			
		]
	},
	{
		path:'/Admin',
		name:'Admin',
		component:()=>import('../views/Admin/index.vue')
	}
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes
})
//防止重复发送请求
let pageData:any;

export function requestData(){
		return new Promise(async (resolve,reject)=>{
			pageData=await getData(localStorage.getItem('token') as string)
			if(pageData.state!=200){
				router.push({
					path:'/'
				})
				resolve(false)
				return;
			}
			resolve(true)
			Store.commit('setPageData',pageData);
		})
	// if(pageData.state!=200)	pageData=await getData(localStorage.getItem('token'));
}
router.beforeEach(async (to,from, next) => {
	//login不检测 
	if(to.path=='/' || to.path=='/404' || to.path=='/singup'){
		next()
		return;
	}
	var flag=await checkToken(Store.getters.getToken);
	
	if(flag){
		if(!pageData){
			var result=await requestData();
		}
			next();
	}else{
		router.replace('/')
	}
})


